package com.zxjbyte.yiyi.framework.common.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.zxjbyte.yiyi.framework.common.constant.StringPool;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 扩展 cn.hutool.core.collection.CollUtil
 * @Author zhangxingjia
 * @Date 2023/4/3 14:44
 * @Version: 1.0
 */
@UtilityClass
public class CollXUtil extends CollUtil {

    /**
     * key value组装map
     * @param keysValues
     * @param <K>
     * @param <V>
     * @return
     */
   public <K, V> Map<K, V> of(Object... keysValues){
       int kvLength = keysValues.length;
       Assert.isFalse(kvLength % 2 != 0, "wrong number of arguments for of, keysValues length can not be odd");
       Map<K, V> keyValueMap = new HashMap<>(kvLength);
       for (int i = kvLength - 2; i >= 0; i -= 2) {
           Object key = keysValues[i];
           Object value = keysValues[i + 1];
           keyValueMap.put((K) key, (V) value);
       }
       return keyValueMap;
   }

    /**
     * 多层嵌套的Map，键值用.成字符串作为新Map的键，原来的值作为新Map的值
     * @param map
     * @return
     */
    public Map<String, Object> flattenMap(Map<String, Object> map) {
        return flattenMap(StringPool.EMPTY, map, new HashMap<>());
    }

    private Map<String, Object> flattenMap(String prefix, Map<String, Object> source, Map<String, Object> result) {
        for (Map.Entry<String, Object> entry : source.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof Map) {
                flattenMap(prefix + key + StringPool.DOT, (Map<String, Object>) value, result);
            } else {
                result.put(prefix + key, value);
            }
        }
        return result;
    }

    /**
     * 对list泛型是map结构进行深度克隆
     * @param oldListMaps
     * @return
     */
    public static List<Map<String, Object>> listMapClone(List<Map<String, Object>> oldListMaps){
        List<Map<String, Object>> newListMaps = new ArrayList<>();
        for (Map<String, Object> oldMap : oldListMaps) {
            Map<String, Object> newMap = new HashMap<>(oldMap);  // 创建一个新的 Map，并传递旧 Map 的内容
            newListMaps.add(newMap);  // 将新的 Map 添加到新列表中
        }
        return newListMaps;
    }
}
